from datetime import datetime, timedelta

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
# chat/views.py
from django.shortcuts import render

# 获取房间号
from utils.jwtUtils import generate_jwt
from utils.mongdb_utils import MyMongo
from utils.myLoginView import MyLoginView


class GetRoomNumView(MyLoginView):

    def _generate_tokens(self, param, with_refresh_token=False):
        """
        生成token 和refresh_token
        :param user_id: 用户id
        :return: token, refresh_token
        """
        # 颁发JWT
        now = datetime.utcnow()
        expiry = now + timedelta(hours=5)

        # token = generate_jwt({'user_id': user_id, 'refresh': False}, expiry)
        token = generate_jwt(param, expiry)

        return token

    def get(self, request):
        target = request.GET.get("target")
        if target:
            room_name = self._generate_tokens({"user_id": request.user.id, "target": target})

            return JsonResponse({"code": '200', "message": "OK","room_name":room_name})
        else:
            return JsonResponse({"code":'400',"message":"参数不全"})

class GetUserChatObjects(MyLoginView):

    def get(self,request):

        user = request.user

        # 连接Django
        m = MyMongo('zhaopi','userchats')

        ret = m.work.find_one({'id':str(user.id)})

        return JsonResponse({"code":200,"errmsg":'ok',"data":ret['chats'],"user_id":user.id})
